<template>
  <div>
      <div class="top-main">
      <el-form class="top-form-fl" :model="searchParam" :inline="true" label-width="auto">
        <el-form-item label="箱号">
          <MultipleBoxNumbersDialog v-model.trim="searchParam.containerNo"/>
        </el-form-item>
        <el-form-item  label="业务编号">
          <el-input v-model.trim="searchParam.businessNo" clearable placeholder="请输入业务编号"></el-input>
        </el-form-item>
        <el-form-item label="箱型">
          <el-select v-model="searchParam.boxType" style="width:100%" placeholder="选择箱型">
            <el-option v-for="item in basicConfig.boxTypeInfo" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="箱况">
          <el-select v-model="searchParam.boxCondition" style="width:100%" placeholder="选择箱况">
            <el-option v-for="item in basicConfig.boxConditionInfo" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="箱标">
          <el-select v-model="searchParam.totalWeight" style="width:100%" placeholder="选择箱型">
            <el-option v-for="item in basicConfig.totalWeight" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="买入日期">
          <el-date-picker v-model="searchParam.buyDate" type="daterange" range-separator="~"
                          start-placeholder="开始日期" end-placeholder="结束日期"/>
        </el-form-item>
        <el-form-item label="买箱城市">
          <SelectCity :selectCityId="searchParam.buyCityId" :index="1" :config="{}" @cityId="buyBoxCity"></SelectCity>
        </el-form-item>
        <el-form-item label="集装箱公司">
          <el-input v-model.trim="searchParam.boxEastCompanyName" clearable placeholder="请输入集装箱公司"></el-input>
        </el-form-item>
        <el-form-item label="提箱日期">
          <el-date-picker v-model="searchParam.packingDate" type="daterange" range-separator="~"
                          start-placeholder="开始日期" end-placeholder="结束日期"/>
        </el-form-item>
        <el-form-item label="提箱地址">
          <el-input v-model.trim="searchParam.packingAddress" clearable placeholder="请输入提箱地址"></el-input>
        </el-form-item>
        <el-form-item label="进场日期">
          <el-date-picker v-model="searchParam.inDate" type="daterange" range-separator="~" start-placeholder="开始日期"
                          end-placeholder="结束日期"/>
        </el-form-item>

        <el-form-item label="存箱堆场">
          <SelectYard :selectYardName="searchParam.yardName" :reqType="'yardName'" :config="{}" @yardId="boxStorageYard"
                      style="width:100%"></SelectYard>
        </el-form-item>
      </el-form>
     <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="restSearch">重置</el-button>
      </div>   
    </div>
    <div class="elCard marginTop20">
      <el-row justify="end" align="middle">
        <el-col :span="2" class="text-center">
          <el-dropdown placement="top" size="small">
            <el-button size="small">
              <el-icon>
                <Menu/>
              </el-icon>
              批量操作
            </el-button>
            <template #dropdown>
              <el-dropdown-menu >
                <el-dropdown-item @click="dialogBatchImport=true">导入</el-dropdown-item>
                <el-dropdown-item @click="batchExport">导出</el-dropdown-item>
                <el-dropdown-item @click="deleteItems">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
        <el-col :span="2" class="text-center">
          <el-button type="primary" @click="addBox" size="small">
            <el-icon>
              <Plus/>
            </el-icon>
            添加
          </el-button>
        </el-col>
      </el-row>
    </div>
    <Table ref="tableRef" v-bind="tableInfo" :disableHeaderCheckbox="false" style="width:100%;"
           @pageChange="onTablePageChange" @activDelete="activDelete" @activEdit="activEdit"></Table>

    <!-- 添加/编辑 购箱记录 -->
    <el-dialog v-model="dialogAddContainer" width="1000" @close="cancel">
      <span class="_before">{{ dialogTitle }}</span>
      <el-row v-if="!isEdit" class="marginTop10">
        <el-col :offset="1" :span="23">
          <el-radio-group v-model="haveBoxNumber">
            <el-radio value="1" size="large">有箱号</el-radio>
            <el-radio value="0" size="large">无箱号</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <el-form ref="addFormRef" :model="containerInfo" :label-position="'right'" label-width="auto" :rules="formRules"
               inline class="form-inline">
        <el-form-item v-if="haveBoxNumber == '1'" label="箱号" prop="containerNo">
          <div class="line-content">
            <el-input v-model.trim="containerInfo.containerNo" maxlength="100" placeholder="请输入" clearable/>
          </div>
        </el-form-item>
        <el-form-item label="箱型" prop="boxType">
          <div class="line-content">
            <el-select v-model="containerInfo.boxType" style="width:100%" placeholder="请选择">
              <el-option v-for="item in basicConfig.boxTypeInfo" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="箱况" prop="boxCondition">
          <div class="line-content">
            <el-select v-model="containerInfo.boxCondition" style="width:100%" placeholder="请选择">
              <el-option v-for="item in basicConfig.boxConditionInfo1" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item v-if="haveBoxNumber == '1'" label="箱标" prop="totalWeight">
          <div class="line-content">
            <el-select v-model="containerInfo.totalWeight" style="width:100%" placeholder="请选择">
              <el-option v-for="item in basicConfig.totalWeight" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="业务编号" prop="businessNo">
          <div class="line-content">
            <el-input v-model.trim="containerInfo.businessNo" maxlength="100" placeholder="请输入" clearable/>
          </div>
        </el-form-item>
        <el-form-item label="集装箱公司" prop="boxEastCompanyName">
          <div class="line-content">
            <el-input v-model.trim="containerInfo.boxEastCompanyName" maxlength="100" placeholder="请输入" clearable/>
          </div>
        </el-form-item>
        <el-form-item label="买入日期" prop="buyDate">
          <div class="line-content">
            <el-date-picker v-model="containerInfo.buyDate" type="date" placeholder="请选择日期"
                            :disabled-date="disabledDate" style="width:100%"/>
          </div>
        </el-form-item>
        <el-form-item label="买入价1" prop="buyInPrice">
          <el-row class="line-content elRow">
            <el-col :span="7" class="removeBorder">
              <el-select v-model="containerInfo.currency" size="small">
                <el-option label="$" value="USD"></el-option>
                <el-option label="￥" value="CNY"></el-option>
              </el-select>
            </el-col>
            <el-col :span="17" class="removeBorder">
              <el-input v-model.trim="containerInfo.buyInPrice" placeholder="请输入"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item v-if="haveBoxNumber == '0'" label="购箱量" prop="boxQuantity">
          <div class="line-content">
            <el-input v-model.trim="containerInfo.boxQuantity" placeholder="请输入" style="width:100%"/>
          </div>
        </el-form-item>
        <el-form-item label="买箱城市" prop="buyCityId">
          <div class="line-content">
            <SelectCity :selectCityId="containerInfo.buyCityId" :index="1" :config="{}"
                        @cityId="addBoxCity"></SelectCity>
          </div>
        </el-form-item>
        <el-form-item label="提箱日期" prop="packingDate">
          <div class="line-content">
            <el-date-picker v-model="containerInfo.packingDate" type="date" placeholder="请选择日期"
                            :disabled-date="disabledDate" style="width:100%"/>
          </div>
        </el-form-item>
        <el-form-item label="提箱地址" prop="packingAddress">
          <div class="line-content">
            <el-input v-model.trim="containerInfo.packingAddress" maxlength="200" placeholder="请输入" clearable/>
          </div>
        </el-form-item>
        <el-form-item v-if="haveBoxNumber == '1'" label="进场日期" prop="inDate">
          <div class="line-content">
            <el-date-picker v-model="containerInfo.inDate" type="date" placeholder="请选择日期" style="width:100%"/>
          </div>
        </el-form-item>
        <el-form-item label="存箱堆场" prop="boxEastYardId">
          <div class="line-content">
            <SelectYard :selectYardName="containerInfo.yardName" :reqType="'yardName'" :config="{}"
                        @yardId="addBoxYardId" style="width:100%"></SelectYard>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width: 89%;">
          <el-input v-model.trim="containerInfo.remark" type="textarea" :formatter="containsEmoji" show-word-limit
                    maxlength="200" rows="2"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="restContainerInfo">重置</el-button>
          <el-button type="primary" @click="submitBuyBoxRecords">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 批量导入弹窗 -->
    <el-dialog v-model="dialogBatchImport" width="400">
      <span class="_before">批量导入</span>
      <p class="text-right">
        <el-button link size="small" type="primary">
          <el-icon>
            <Download/>
          </el-icon>
          <a href="http://192.168.1.253:9000/default/template/%E9%9B%86%E8%A3%85%E7%AE%B1%E8%B4%AD%E7%AE%B1%E8%AE%B0%E5%BD%95%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx ">下载模板</a>
        </el-button>
      </p>
      <UploadFilesImages ref="attachmentRef1" :type="'xls/xlsx'" :displayType="1" :purpose="'import'" :use="'record'"
                         :drag="true" @uploadSuccess="uploadSuccess" @excelUploadError="updateInfo"></UploadFilesImages>

    </el-dialog>

    <el-dialog v-model="dialogExcelUploadError"> <!--导入时信息提示-->
      <template v-if="errorType == 'E0001'">
        <span class="_before">错误提示</span>
        <div style="margin: 20px 0;">异常数据<span
            style="color: #f59127;">{{ dialogExcelUploadErrordInfo.length || "--" }}</span>条，下面是有异常的信息，请您修改后重新导入
        </div>
        <el-table :data="dialogExcelUploadErrordInfo" border style="width: 100%">
          <el-table-column prop="rowNum" label="异常位置" align="center" width="200">
            <template #default="scope">第{{ scope.row.rowNum }}行</template>
          </el-table-column>
          <el-table-column prop="errorMsg" label="异常原因" align="center"/>
        </el-table>
      </template>
      <template v-else-if="errorType == 'B0001'">
        <span class="_before">错误提示</span>
        <div style="margin: 20px 0;text-align: center;">{{ dialogExcelUploadErrordInfo }}</div>
      </template>
      <template v-else>
        <span class="_before">成功提示</span>
        <div style="margin: 20px 0;text-align: center;">{{ dialogExcelUploadErrordInfo }}</div>
      </template>

      <el-row justify="center" class="marginTop20">
        <el-col :span="3" class="text-center">
          <el-button type="primary" @click="dialogExcelUploadError=false;getTableData()">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog.vue'
import {formatContainerNo} from '@/utils/mlpBox' // 格式化箱号
import {reactive, ref, onMounted, onActivated} from 'vue'
import basicConfig from '@/constant/containerInfo';
import SelectCity from '@/components/citySelect/selectCity'
import SelectYard from '@/components/citySelect/selectYard'
import Table from '@/components/table'
import {
  boxRecords,
  buyBoxRecords,
  deleteBuyBoxRecords,
  exportBuyBoxRecord,
  editBoxRecords
} from '@/api/boxManage/BoxRecords'
import {ElMessage, ElMessageBox} from 'element-plus'
import UploadFilesImages from '@/components/upload/uploadFiles-Images'
import {downloadFile} from '@/utils/download'
import { containsEmoji} from '@/utils'

const searchParam = reactive({
  pageNum: '1',
  pageSize: '10',
  containerNo: '',
  businessNo: '',
  boxType: '',
  boxCondition: '',
  totalWeight: '',
  buyDate: null,
  buyCityId: '',
  boxEastCompanyName: '',
  packingDate: null,
  packingAddress: '',
  inDate: null,
  yardName: '',
  boxEastYardId: '',
})
const addFormRef = ref()
const buyBoxCity = (id: string) => {
  searchParam.buyCityId = id
}
const addBoxCity = (id: string) => {
  containerInfo.buyCityId = id
}
const boxStorageYard = (info: string) => {
  searchParam.yardName = info[0]?.yardName
  searchParam.boxEastYardId = info[0]?.id
}
const addBoxYardId = (info: string) => {
  containerInfo.boxEastYardId = info[0]?.id
}
const tableInfo = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    {key: 'containerNo', colWidth: '120', title: '箱号', type: 'text', isCheck: true},
    {key: 'businessNo', colWidth: '120', title: '业务编号', type: 'text', isCheck: true},
    {key: 'boxType', colWidth: '80', title: '箱型', type: 'filter', filter: basicConfig.boxTypeInfo1, isCheck: true},
    {
      key: 'boxCondition',
      colWidth: '80',
      title: '箱况',
      type: 'filter',
      filter: basicConfig.boxConditionInfo2,
      isCheck: true
    },
    {key: 'totalWeight', colWidth: '80', title: '箱标', type: 'text', isCheck: true},
    {key: 'boxEastCompanyName', colWidth: '150', title: '集装箱公司', type: 'text', isCheck: true},
    {key: 'buyDate', colWidth: '100', title: '买入日期', type: 'date', isCheck: true},
    {key: 'boxQuantity', colWidth: '80', title: '购买量', type: 'text', isCheck: true},
    {key: 'buyInPrice', colWidth: '100', title: '买入价', currency: "currency", type: 'add', isCheck: true},
    {key: 'buyCityName', colWidth: '80', title: '买箱城市', type: 'text', isCheck: true},
    {key: 'packingDate', colWidth: '100', title: '提箱日期', type: 'date', isCheck: true},
    {key: 'inDate', colWidth: '100', title: '进场日期', type: 'date', isCheck: true},
    {key: 'yardName', colWidth: '100', title: '存箱堆场', type: 'text', isCheck: true},
    {key: 'remark', colWidth: '120', title: '备注', type: 'text', isCheck: true},
    {
      key: 'operate',
      colWidth: '180',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          //   icon: 'Edit',
          command: 'activEdit',
          //   content: '编辑',
          name: '编辑'
          // isShow: (row) => {
          //   return row.activityId == '1';
          // },
        },
        {
          //   icon: 'Delete',
          command: 'activDelete',
          //   content: '删除',
          name: '删除'
          //   isShow: (row: { status: string; }) => {
          //     return row.status == '5' || row.status == '30';
          //   },
        }
      ],
    }
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
})
const formRules = {// 表单验证规则
  containerNo: [
    {required: true, trigger: "change", message: "箱号不能为空"},
    {pattern: /^[A-Z]{3}U\d{7}$/, trigger: "change", message: "请输入正确格式的箱号"}
  ],
  boxType: [{required: true, trigger: "change", message: "请选择箱型"}],
  boxCondition: [{required: true, trigger: "change", message: "请选择箱况"}],
  totalWeight: [{required: true, trigger: "change", message: "请选择箱标"}],
  businessNo: [
    {required: true, trigger: "change", message: "业务编号不能为空"},
    {pattern: /^[a-zA-Z0-9]+$/, message: '只能输入字母和数字', trigger: 'blur'},
    {max: 20, message: '只能输入20个字符', trigger: 'blur'}
  ],
  boxEastCompanyName: [
    {required: true, trigger: "change", message: "集装箱公司不能为空"},
    {max: 200, trigger: "blur", message: "最多输入200位"},
    {
      validator: (rule, value, callback) => {
        if (!validateInternationalText(value)) {
          callback(new Error('只能输入各国文字（禁止数字和特殊符号）'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  buyDate: [{required: true, trigger: "change", message: "买入日期不能为空"}],
  buyInPrice: [
    {required: true, trigger: "change", message: "买入价不能为空"},
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入金额'));
          return;
        }
         // 验证数值范围
         const num = parseFloat(value);
        if (isNaN(num)) {
          callback(new Error('请输入有效数字'));
        } else if (num < 0) {
          callback(new Error('价格不能为负数'));
        } else if(!/^-?\d{0,5}(\.\d{0,1000})?$/.test(value)){
          callback(new Error('只能输入数字,整数部分不超过5位'));
          return;
        } else if(!/^-?\d{0,5}(\.\d{0,2})?$/.test(value)){
          callback(new Error('只能输入数字，小数部分不超过2位'));
          return;
        } else if(value.endsWith('.')){
          callback(new Error('不能以小数点结尾'));
        }else {
          callback();
        }
       
      },
      trigger: 'blur'
    }
  ],
  boxQuantity: [
    {required: true, trigger: "change", message: "购箱量不能为空"},
    {pattern: /^[1-9]\d*$/, trigger: "change", message: "请输入正确箱量"}
  ],
  buyCityId: [{required: true, trigger: "change", message: "买箱城市不能为空"}],
  packingDate: [{required: true, trigger: "change", message: "提箱日期不能为空"}],
  packingAddress: [
    {required: true, trigger: "change", message: "提箱地址不能为空"},
    {
      validator: (rule, value, callback) => {
        if (!validateInternationalText(value)) {
          callback(new Error('只能输入各国文字（禁止数字和特殊符号）'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  inDate: [{required: true, trigger: "change", message: "进场日期不能为空"}],
  boxEastYardId: [{required: true, trigger: "change", message: "存箱堆场不能为空"}],
  remark: [{max: 500, message: '内容长度不能超过500个字符', trigger: 'blur'}]
}
const validateInternationalText = (value) => {
  // 主要语言的Unicode范围：
  // 中文: \u4e00-\u9fa5
  // 日文: \u3040-\u309F（平假名）, \u30A0-\u30FF（片假名）, \u4e00-\u9faf（汉字）
  // 韩文: \uAC00-\uD7AF
  // 西文（拉丁）: \u00C0-\u00FF（带重音）, \u0100-\u017F（扩展拉丁）
  // 俄文: \u0400-\u04FF
  // 希腊文: \u0370-\u03FF
  // 阿拉伯文: \u0600-\u06FF
  // 希伯来文: \u0590-\u05FF
  // 泰文: \u0E00-\u0E7F
  const internationalRegex = /^[\u4e00-\u9fa5\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF\u00C0-\u00FF\u0100-\u017F\u0400-\u04FF\u0370-\u03FF\u0600-\u06FF\u0590-\u05FF\u0E00-\u0E7F\s]+$/;
  return internationalRegex.test(value);
}

const dialogTitle = ref('添加购箱记录')
const dialogAddContainer = ref(false)
const haveBoxNumber = ref("1") // 是否有箱号
const containerInfo = reactive({
  id: '',
  containerNo: '',
  boxType: '',
  boxCondition: '',
  totalWeight: '',
  businessNo: '',
  boxEastCompanyName: '',
  buyDate: '',
  buyInPrice: '',
  currency: 'USD',
  boxQuantity: '',
  buyCityId: '',
  packingDate: '',
  packingAddress: '',
  inDate: '',
  yardName: '',
  boxEastYardId: '',
  remark: ''
})
//添加集装箱
const addBox = () => {
  // restContainerInfo()
  dialogTitle.value = '添加购箱记录'
  dialogAddContainer.value = true
}
// 确定新增购箱记录
const submitBuyBoxRecords = () => {
  let reqParam = {
    containerNo: haveBoxNumber.value == "1" ? containerInfo.containerNo : null,
    boxType: containerInfo.boxType,
    boxCondition: containerInfo.boxCondition,
    totalWeight: haveBoxNumber.value == "1" ? containerInfo.totalWeight : null,
    businessNo: containerInfo.businessNo,
    boxEastCompanyName: containerInfo.boxEastCompanyName,
    buyDate: containerInfo.buyDate,
    buyInPrice: containerInfo.buyInPrice,
    currency: containerInfo.currency,
    boxQuantity: haveBoxNumber.value == "0" ? containerInfo.boxQuantity : null,
    buyCityId: containerInfo.buyCityId,
    packingDate: containerInfo.packingDate,
    packingAddress: containerInfo.packingAddress,
    inDate: haveBoxNumber.value == "1" ? containerInfo.inDate : null,
    boxEastYardId: haveBoxNumber.value == "1" ? containerInfo.boxEastYardId : null,
    remark: containerInfo.remark
  }
  if (isEdit.value) { // 重新编辑/修改
    reqParam.id = containerInfo.id
    editBoxRecords(reqParam).then(res => {
      if (res.code == "00000") {
        ElMessage.success("购箱记录修改成功！")
        restContainerInfo()
        getTableData()
        dialogAddContainer.value = false
      } else {
        ElMessage.warning("购箱记录修改失败，请刷新页面！")
      }
    })
  } else {
    buyBoxRecords(reqParam).then((res: any) => {
      if (res.code == "00000") {
        ElMessage.success("购箱记录添加成功！")
        restContainerInfo()
        getTableData()
        dialogAddContainer.value = false
      } else {
        ElMessage.warning("购箱记录添加失败，请刷新页面！")
      }
    })
  }
}
// 清空添加提箱记录输入内容
const restContainerInfo = () => {
  // if(!isEdit.value){
  //     containerInfo.containerNo = ''
  // }
  isEdit.value = false
  containerInfo.containerNo = ''
  containerInfo.boxType = '',
      containerInfo.boxCondition = '',
      containerInfo.totalWeight = '',
      containerInfo.businessNo = '',
      containerInfo.boxEastCompanyName = '',
      containerInfo.buyDate = '',
      containerInfo.buyInPrice = '',
      containerInfo.currency = 'USD',
      containerInfo.boxQuantity = '',
      containerInfo.buyCityId = '',
      containerInfo.packingDate = '',
      containerInfo.packingAddress = '',
      containerInfo.inDate = '',
      containerInfo.yardName = '',
      containerInfo.boxEastYardId = '',
      containerInfo.remark = ''
}
// 批量导入
const dialogBatchImport = ref(false)
// const  = () => {

// }

// 选中的购箱记录
const tableRef = ref({multipleSelection: []})

// 批量导出
const batchExport = () => {
  const selectIds = tableRef.value.multipleSelection.map((item: any) => item.id)
  let buyBoxRecordIds = {
    buyBoxRecordIds: selectIds
  }
  if (selectIds.length > 0) {
    exportBuyBoxRecord(buyBoxRecordIds).then(res => {
      downloadFile(res, '集装箱购箱记录')
    })
  } else {
    ElMessage.warning('请选择需要导出的购箱记录')
  }

}


// 编辑购箱记录
const isEdit = ref(false) //是否是重新编辑集装箱
const activEdit = (row: any) => {
  containerInfo.id = row.id
  containerInfo.boxType = row.boxType
  containerInfo.boxCondition = row.boxCondition
  containerInfo.businessNo = row.businessNo
  containerInfo.boxEastCompanyName = row.boxEastCompanyName
  containerInfo.buyDate = row.buyDate
  containerInfo.buyInPrice = row.buyInPrice
  containerInfo.currency = row.currency
  containerInfo.boxQuantity = row.boxQuantity
  containerInfo.buyCityId = row.buyCityId
  containerInfo.packingDate = row.packingDate
  containerInfo.packingAddress = row.packingAddress
  containerInfo.remark = row.remark
  if (row.containerNo) {
    haveBoxNumber.value = "1"  //有箱号
    containerInfo.containerNo = row.containerNo
    containerInfo.totalWeight = row.totalWeight
    containerInfo.inDate = row.inDate
    containerInfo.yardName = row.yardName
    containerInfo.boxEastYardId = row.boxEastYardId
  } else {
    haveBoxNumber.value = "0"  //无箱号
  }
  isEdit.value = true
  dialogTitle.value = '编辑购箱记录'
  dialogAddContainer.value = true
}
// 单个删除
const activDelete = (row: any) => {
  let ids = [row.id]
  ElMessageBox.confirm(
      '此条购箱记录相关费用已生成，请谨慎操作，删除后不可恢复！',
      '提示',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '暂不删除',
        type: 'warning',
      }).then(() => {
    deleteData(ids)
  }).catch(() => {
  })
}
// 批量删除
const deleteItems = () => {
  const selectIds = tableRef.value.multipleSelection.map((item: any) => item.id)
  if (selectIds.length > 0) {
    ElMessageBox.confirm(
        '选中购箱记录相关费用已生成，请谨慎操作，删除后不可恢复！',
        '提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '暂不删除',
          type: 'warning',
        }
    ).then(() => {
      deleteData(selectIds)
    }).catch(() => {
    })

  } else {
    ElMessage.warning('请选择要删除的数据')
  }
}
const deleteData = (val: Array<any>) => {
  deleteBuyBoxRecords(val).then(res => {
    if (res.code == '00000') {
      ElMessage.success("购箱记录删除成功！")
      getTableData()
    } else {
      ElMessage.error(res.message)
    }
  })
}
//关闭弹框
const cancel = () => {
  addFormRef.value.resetFields()// 重置数据
  restContainerInfo()
  dialogAddContainer.value = false
}
// 清空搜索搜索信息
const restSearch = () => {
  searchParam.containerNo = "",
      searchParam.businessNo = "",
      searchParam.boxType = "",
      searchParam.boxCondition = "",
      searchParam.totalWeight = "",
      searchParam.buyCityId = "",
      searchParam.boxEastCompanyName = "",
      searchParam.packingDate = null,
      searchParam.packingAddress = "",
      searchParam.inDate = null,
      searchParam.yardName = "",
      searchParam.boxEastYardId = "",
      searchParam.buyDate = null
  getTableData()
}

const dialogExcelUploadError = ref(false)
const dialogExcelUploadErrordInfo = ref()
const errorType = ref()
const attachmentRef1 = ref()

const updateInfo = (info: any) => {
  dialogExcelUploadError.value = true
  if (info.code == "E0001") {
    errorType.value = 'E0001'
    dialogExcelUploadErrordInfo.value = JSON.parse(info.data)
  } else if (info.code == "B0001") {
    errorType.value = 'B0001'
    dialogExcelUploadErrordInfo.value = info.msg
  } else {
    errorType.value = '00000'
    dialogBatchImport.value = false
    dialogExcelUploadErrordInfo.value = "购箱记录导入成功！"

  }
  attachmentRef1.value.clearFiles()
}
// onActivated(()=>{ 
//     console.log('1111')
//     getTableData()
// })
onMounted(() => {
  getTableData()
})

// 获取列表数据
function getTableData() {
  const {container, containerList} = formatContainerNo(searchParam.containerNo);
  let reqParam = {
    pageNum: searchParam.pageNum,
    pageSize: searchParam.pageSize,
    containerNo: container, // 单箱号查询
    containerNos: containerList, // 多箱号查询
    businessNo: searchParam.businessNo,
    boxType: searchParam.boxType,
    boxCondition: searchParam.boxCondition,
    totalWeight: searchParam.totalWeight,
    // beginBuyDate:searchParam.buyDate[0],
    // endBuyDate:searchParam.buyDate[1],
    buyCityId: searchParam.buyCityId,
    boxEastCompanyName: searchParam.boxEastCompanyName,
    // beginPackingDate:searchParam.packingDate[0],
    // endPackingDate:searchParam.packingDate[1],
    packingAddress: searchParam.packingAddress,
    // beginInDate:searchParam.inDate[0],
    // endInDate:searchParam.inDate[1],
    boxEastYardId: searchParam.boxEastYardId
  }

  if (searchParam.buyDate && searchParam.buyDate.length > 1) {
    reqParam.beginBuyDate = searchParam.buyDate[0]
    reqParam.endBuyDate = searchParam.buyDate[1]
  }
  if (searchParam.packingDate && searchParam.packingDate.length > 1) {
    reqParam.beginPackingDate = searchParam.packingDate[0]
    reqParam.endPackingDate = searchParam.packingDate[1]
  }
  if (searchParam.inDate && searchParam.inDate.length > 1) {
    reqParam.beginInDate = searchParam.inDate[0]
    reqParam.endInDate = searchParam.inDate[1]
  }
  boxRecords(JSON.parse(JSON.stringify(reqParam))).then(res => {
    if (res && res.code == '00000') {
      tableInfo.data = res.data.list
      console.log(res);
      tableInfo.config.total = res.data.total;
    }

  });
}

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}


// 上传集装箱成功调用
const uploadSuccess = (_row: any) => {
  getTableData();
  dialogBatchImport.value = false
  ElMessage.success({
    message: _row.data,
    duration: 10000
  })

}


//分页
function onTablePageChange(page: any) {
  searchParam.pageNum = page.pageNum;
  searchParam.pageSize = page.pageSize;
  getTableData();
};


</script>
<style lang="scss" scoped>
.elCard {
  margin-left: 20px;
  margin-right: 20px;
}

.form-inline {
  margin-top: 20px;

  .line-content {
    width: 200px;
  }
}

.removeBorder {
  :deep(.el-input__wrapper) {
    box-shadow: none !important;
    // height: 30px;
    // border-radius: 0;
  }

  :deep(.el-select__wrapper) {
    box-shadow: none !important;
    // height: 30px;
    // border-radius: 0;
  }
}

.elRow {
  border: 1px solid #ddd;
  border-radius: 3px;
}

.elInput {
  border: 1px solid #ddd;
  border-radius: 3px;
}

</style>